<template>
  <el-form :model="formInline" ref="formInline" style="text-align:center;font-size:20px;" size="medium"
    label-width="230px">
    <!-- 申请户主信息 表单里面(已经在表单里面) -->
    <el-card style="font-size:20px;margin-top:1%">
      基本信息
      <el-row :gutter="10" style>
        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formInline.name" autocomplete="off" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="性别">
            <el-radio-group v-model="formInline.sex" :disabled="true" id="sex">
              <el-radio-button label="男" value="男"></el-radio-button>
              <el-radio-button label="女" value="女"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄（岁）">
            <el-input v-model.number="formInline.age" ref="age" autocomplete="off" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="formInline.idCard" autocomplete="off" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="formInline.tel" placeholder="如果是座机，请加上023" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="户口所在地">
            <el-input v-model="formInline.address" autocomplete="off" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="乡镇街道" prop="townName">
            <el-input v-model="formInline.townName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="村组社区" prop="villageName">
            <el-input v-model="formInline.villageName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拟申请地址">
            <el-input v-model="formInline.applyAddress" class="input-with-select" disabled>
              <el-select v-model="formInline.villageType" slot="append" placeholder="请选择组或社" style="width: 150px;"
                disabled>
                <el-option label="组" value="组"></el-option>
                <el-option label="社" value="社"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="margin-top:1%; font-size:20px; height:250px">
      上传告知书
      <div class="uploadStyle">
        <el-button type="primary" @click="applyFor('执法结果告知书')" style="width:200px;font-size:18px;height:100px">
          <i class="el-icon-upload"></i>执法结果告知书
        </el-button>
      </div>
      <!-- <el-dialog :visible.sync="uploadState" center title="要件上传" :show-close="false"> -->
      <el-dialog :visible.sync="uploadState" center :title="tempName" :show-close="false">
        <el-upload action="#" list-type="picture-card" :auto-upload="false" accept="image/*" multiple
          :http-request="addFile" ref="upload">
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button @click="uploadCancel">取 消</el-button>
          <el-button type="primary" @click="submitUpload">提交</el-button>
        </span>
      </el-dialog>
    </el-card>

    <el-card style="margin-top:1%; font-size:20px">
      要件列表
      <el-table :data="formInline.formFileList" style="margin-top:1%" v-loading @cell-dblclick="editDocName">
        <el-table-column prop="docName" label="要件名称" align="center">
          <editable-cell slot-scope="{row}" :can-edit="editDocNameEnabled" v-model="row.docName">
            <span slot="content">{{row.docName}}</span>
          </editable-cell>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" align="center"></el-table-column>
        <el-table-column prop="operation" label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEditFile(scope.$index, scope.row)" type="primary">预览</el-button>
            <el-button size="mini" @click="handleDeleteFile(scope.$index, scope.row)" type="info">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card style="margin-top:1%">
      意见
      <br />
      <el-input ref="initState" type="textarea" placeholder="请填写意见" style="margin-top:10px;width=50%"
        v-model="formInline.opinion"></el-input>
    </el-card>
    <el-card style=" margin-top:1%;margin-bottom:1%">
      <el-button type="primary" style="width:100px;font-size:18px" @click="commitPro('formInline')">提交</el-button>
      <el-button type="danger" style="width:100px;font-size:18px" @click="cancle">取消</el-button>
    </el-card>
  </el-form>
</template>
<script>
  import store from "@/vuex/store";
  import {
    saveProApi,
    commitProApi,
    returnProApi,
    queryIdCordApi,
  } from "@/api/applyApi";
  import {
    getFamilyMenberByBiidApi
  } from "@/api/familyMenberApi";
  import {
    getDocumentListApi,
    downDocumentApi,
    deleteDocument,
  } from "@/api/documentApi";
  import {
    queryOpinionByApplyCodeApi
  } from "@/api/opinionApi";
  import {
    getChildrenAddress
  } from "@/api/addressDictionary";
  import axios from "axios";
  import config from "@/config/config";
  import EditableCell from "./component/editCell.vue";
  import {
    returnCompleteApi
  } from "@/api/completApi";
  export default {
    name: "putBussi",
    components: {
      EditableCell,
    },
    data() {
      return {
        tempName: "",
        fileName: "",
        previewVisible: false,
        uploadState: false,
        photoPathArray: [],
        photoPath: "",
        imgPathArray: [],
        imgPath: "",
        department: "",
        generateDocList: [],
        generateDocState: false,
        idCardState: true,
        socket: null,
        dialog: null,
        uid: store.getters.uid,
        showTownState: false,
        preUrl: "",
        confirmUrl: "",
        cameraState: false,
        centerDialogVisible: false,
        url: "",
        currentCode: store.getters.currentCode,
        opinionInfo: [{
          uName: "",
          opinion: "",
          state: "",
          order: "",
          submitTime: "",
        }, ],
        activeName: "second",
        initState: false,

        formFile: new FormData(),
        fileData: "",
        formInline: {
          formFileList: [],
          applyCode: null, //业务编号
          name: "", //申请人姓名
          sex: "", //性别
          tel: null, //电话
          idCard: "", //身份证号
          address: "", //户口所在地
          age: null, //年龄
          nowHomesteadArea: null, //现宅基地面积
          nowBuildArea: null, //现建筑面积
          nowBookId: "", //现权属证书号
          nowSaveArea: "", //现保留面积
          nowReturnArea: "", //退给村集体面积
          nowOtherArea: "", //其他面积
          applyHomesteadArea: "", //拟申请宅基地面积
          applyFoundationArea: "", //拟申请房基占地面积
          applyAddress: "", //拟申请宅基地及建房地址
          east: "", //东至
          south: "", //南至
          west: "", //西至
          north: "", //北至
          buildingType: "", //建房类型
          landType: "", //地类
          applyHousingArea: "", //住房建筑面积
          applyLayer: "", //层数
          applyHight: "", //高度
          neighborMind: "", //邻居意见
          townCode: "", //乡镇街道代码
          villageCode: "", //村组社区代码
          townList: [], //乡镇街道列表
          villageList: [], //村组社区列表
          opinion: "", //意见
          content: "",
        },
        editDocNameEnabled: false,
        fileCommitState: false,
      };
    },
    created: function () {
      this.formInline = this.$route.query;
      console.log(this.formInline);
      this.showTown();
    },

    methods: {
      //编辑要件名称
      editDocName(row, column, cell, event) {
        this.editDocNameEnabled = true;
      },
      //取消上传
      uploadCancel() {
        this.formFile = new FormData();
        this.uploadState = false;
        this.$refs.upload.clearFiles();
      },
      //提交上传
      submitUpload() {
        const loading = this.$loading({
          //打开加载等待效果
          lock: true,
          text: "正在上传",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        let configs = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };

        this.$refs.upload.submit();
        if (!this.fileCommitState) {
          this.$message.error("请选择文件");
          loading.close();
          return;
        }

        if (this.formInline.applyCode) {
          this.formFile.append("applyCode", this.formInline.applyCode);
        } else {
          this.formFile.append("currentCode", this.currentCode);
        }

        this.formFile.append("token", store.getters.token);
        this.formFile.append("name", this.fileName);
        // this.formFile.append("applyCode", response.data.data.applyCode);
        axios
          .post(config.lawFileUrl, this.formFile, configs)
          .then((res) => {
            this.$message.success("提交成功");
            loading.close();
            this.formInline.applyCode = res.data.applyCode;
            this.formInline.formFileList.push(res.data);
            console.log(res);
            this.formFile = new FormData();
            this.uploadState = false;
            this.$refs.upload.clearFiles();
            this.fileCommitState = true;
          })
          .catch((err) => {
            loading.close();
          });
      },
      addFile(file) {
        this.formFile.append("files", file.file);
        this.fileCommitState = true;
      },
      showTown() {
        if (this.currentCode.length > 9) {
          this.showTownState = true;
        } else {
          this.showTownState = false;
          this.formInline.townCode = this.currentCode;
        }
      },
      //改变乡镇
      townChange() {
        if (this.formInline.townCode) {
          getChildrenAddress(this.formInline.townCode).then((villageList) => {
            this.formInline.villageList = villageList.data.data;
            this.formInline.villageCode = this.formInline.villageList[0].code;
          });
        }
      },
      //提交
      commitPro() {
        this.formInline.uid = this.uid;
        const loading = this.$loading({
          //打开加载等待效果
          lock: true,
          text: "正在提交",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$confirm("是否提交到竣工验收阶段?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            returnCompleteApi(this.formInline)
              .then((response) => {
                this.$message({
                  showClose: true,
                  message: "提交成功",
                  type: "success",
                });
                loading.close(); //瞬间没得
                this.$router.go(-1);
              })
              .catch((error) => {
                console.log(error);
                this.$message({
                  showClose: true,
                  message: error,
                  type: "error",
                });
                loading.close();
              });
          })
          .catch((e) => {
            console.log(e);
            this.$message({
              type: "info",
              message: "取消提交",
            });
            loading.close();
          });
      },
      //删除要件
      handleDeleteFile(index, row) {
        if (row.url) {
          deleteDocument(row)
            .then((res) => {
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success",
              });
              this.formInline.formFileList.splice(index, 1);
              // this.formFile.delete(row.fileName);
              // this.getDocumentList(this.formInline.applyCode);
            })
            .catch((error) => {
              console.log(error);
              this.$message({
                showClose: true,
                message: "删除失败！",
                type: "error",
              });
            });
        } else {
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          this.formInline.formFileList.splice(index, 1);
          this.formFile.delete(row.fileName);
        }
      },
      //下载要件
      downDocument(index, row) {
        downDocumentApi(row.id);
        this.$message({
          showClose: true,
          message: "下载成功",
          type: "success",
        });
      },
      //新增家庭成员时，点击取消，将数据清空
      putMemberCancel() {
        this.memberDetail = {
          listId: "",
          name: "",
          age: "",
          address: "",
          relation: "",
          idcard: "",
          applyCode: this.formInline.applyCode,
        };

        this.putFailyState = false;
      },
      cancle() {
        this.$router.go(-1);
      },
      //预览handleEditFile
      handleEditFile(index, row) {
        if (row.url) {
          var previewUrl = row.url.split(":");
          var url = config.baseUrl + previewUrl[1];
          if (/\.(jpe?g|png|gif)$/i.test(row.url)) {
            this.url = url;
            this.srcList = url;
            this.centerDialogVisible = true;
          } else {
            window.open(url, "_blank");
          }
          // window.open(config.baseUrl + previewUrl[1], "_blank");
        } else {
          // window.open(row.file);
          // this.$message.error("当前业务未提交（暂存），无法预览！");
          if (/\.(jpe?g|png|gif)$/i.test(row.file.name)) {
            let url = URL.createObjectURL(row.file);
            // window.open(url, "_blank");
            this.url = url;
            this.srcList = url;
            this.centerDialogVisible = true;
          } else if (/\.(pdf)$/i.test(row.file.name)) {
            var win = window.open();
            var reader = new FileReader(); //文件读取器
            reader.readAsDataURL(row.file);
            reader.onload = function () {
              var result = reader.result;

              win.document.write(
                '<body style="margin:0px;"><object data="' +
                result +
                '" type="application/pdf" width="100%" height="100%"><iframe src="' +
                result +
                '" scrolling="no" width="100%" height="100%" frameborder="0" ></iframe></object></body>'
              );
            };
          } else {
            this.$message.error("该类型文件暂不支持预览，请提交后下载下载");
          }
        }
      },
      //上传文件
      applyFor(name) {
        this.tempName = name;
        this.uploadState = true;
        this.fileName = name;
      },
      getCurrentTime() {
        var myDate = new Date();
        var year = myDate.getFullYear();
        var mounth = myDate.getMonth() + 1;
        var day = myDate.getDate();
        var getUplodTime = year + "-" + mounth + "-" + day;
        return getUplodTime;
      },
    },
    mounted() {},
  };
</script>
<style>
  .uploadStyle {
    margin: 1% 0 1% 0;
    text-align: center;
    height: 100px;
    font-size: 18px;
  }
</style>